package com.richapp.launcher.service;

import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;
import android.util.Log;

import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.richapp.launcher.dao.DbHelper;
import com.richapp.launcher.database.infrared.InfraredDatabaseHelper;
import com.richapp.launcher.database.infrared.dao.BrandDao;
import com.richapp.launcher.database.infrared.dao.BrandModelButtonDao;
import com.richapp.launcher.database.infrared.dao.BrandModelDao;
import com.richapp.launcher.database.infrared.dao.ButtonDao;
import com.richapp.launcher.database.infrared.dao.InfraredVersionDao;
import com.richapp.launcher.database.infrared.dao.MachineTypeDao;
import com.richapp.launcher.database.infrared.mode.Button;
import com.richapp.launcher.database.infrared.mode.InfraredVersion;
import com.richapp.launcher.database.infrared.mode.MachineType;
import com.richapp.launcher.utils.HttpUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by yif on 16/9/6.
 */
public class InfraredUpdateServiceBak extends Service {


    private static final String TAG = InfraredUpdateServiceBak.class.getName();
    private ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(4);

    private final static String INFRARED_INFO_URL = "http://www.tasogo.com/share/getupdate.aspx?user=shzy_46IVB1D02H2LDU7THE8D";

    private InfraredVersionDao infraredVersionDao;
    private MachineTypeDao machineTypeDao;
    private BrandModelButtonDao brandModelButtonDao;
    private ButtonDao buttonDao;
    private BrandDao brandDao;
    private BrandModelDao brandModelDao;

    private String infraredDbName = "infrared.db";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        infraredVersionDao = new InfraredVersionDao(this);
        machineTypeDao = new MachineTypeDao(this);
        brandModelButtonDao = new BrandModelButtonDao(this);
        buttonDao = new ButtonDao(this);
        brandDao = new BrandDao(this);
        brandModelDao = new BrandModelDao(this);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {

                try {
                    boolean needUpdate = false;
                    String response = HttpUtil.get(INFRARED_INFO_URL);
                    if (response == null || "".equals(response.trim())) {
                        Log.e(TAG, "请求版本库信息返回为空");
                        return;
                    }

                    InfraredVersion infraredVersion = parseInfraredInfo(response);
                    if (infraredVersion == null) {
                        Log.e(TAG, "版本库信息解析为空");
                        return;
                    }

                    InfraredVersion infraredVersionDb = infraredVersionDao.getFirst();
                    if (infraredVersionDb == null)
                        return;
                    if (infraredVersion.getDbVersion() > infraredVersionDb.getDbVersion()) {
                        infraredVersion.setId(infraredVersionDb.getId());
                        needUpdate = true;
                    }

                    if (needUpdate) {
                        //TODO 下载DB,更新数据库数据
                        String dirPath = "/data/data/" + getApplicationContext().getPackageName() + "/databases" + File.separator;
                        String fileName = "temp.db";
                        downloadFile(dirPath, fileName, infraredVersion.getDbUrl());
                        reBuildDb(infraredVersion);
                    }
                } catch (Exception e) {
                    Log.e(InfraredUpdateServiceBak.class.getName(), "更新红外数据错误", e);
                }

            }


        }, 20, 60, TimeUnit.SECONDS);

        return super.onStartCommand(intent, flags, startId);
    }


    private InfraredVersion parseInfraredInfo(String response) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        InfraredVersion infraredVersion = new InfraredVersion();
        String[] fields = response.split("\\|");
        if (fields.length != 8) {
            return null;
        }
        infraredVersion.setApiVersion(Integer.valueOf(fields[0]));
        infraredVersion.setApiUpdateTime(sdf.parse(fields[1]));
        infraredVersion.setApiDesc(fields[2]);
        infraredVersion.setApiUrl(fields[3]);

        infraredVersion.setDbVersion(Integer.valueOf(fields[4]));
        infraredVersion.setDbUpdateTime(sdf.parse(fields[5]));
        infraredVersion.setDbDesc(fields[6]);
        infraredVersion.setDbUrl(fields[7]);

        return infraredVersion;
    }

    private void downloadFile(String dirPath, String fileName, String url) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdir();
        }
        InputStream is = null;
        OutputStream os = null;
        try {
            URL url2 = new URL(url);
            URLConnection con = url2.openConnection();
            is = con.getInputStream();
            byte[] bs = new byte[1024];
            int len;
            os = new FileOutputStream(dirPath + fileName);
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {

            }
        }
    }

    private void reBuildDb(InfraredVersion infraredVersion) {


        String dirPath = "/data/data/" + getApplicationContext().getPackageName() + "/databases" + File.separator;
        File file = new File(dirPath + infraredDbName);
//        if (file.exists()) {
//            file.delete();
//        }
        File file2 = new File(dirPath + "temp.db");
//        file2.renameTo(file);

        ConnectionSource cs = InfraredDatabaseHelper.getHelper(this).getConnectionSource();
        SQLiteDatabase db = new DbHelper(this, dirPath + "temp.db", null, 2).getReadableDatabase();
        try {
            createMachineTypeTable(cs, db);
            createButtonTable(cs, db);
            createBrandTable(cs, db);
            createBrandModelTable(cs, db);
            createBrandModelButtonTable(cs, db);
            createInfraredVersionTable(cs, db, infraredVersion);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }


//        if (machineTypes != null && !machineTypes.isEmpty()) {
//            machineTypeDao.deleteAll();
//            for (MachineType machineType : machineTypes) {
//                machineTypeDao.add(machineType);
//            }
//        }
//        Log.e(TAG, machineTypeDao.getList().size() + "");
    }

    private void createBrandModelButtonTable(ConnectionSource cs, SQLiteDatabase db) {

    }

    private void createBrandModelTable(ConnectionSource cs, SQLiteDatabase db) {

    }

    private void createBrandTable(ConnectionSource cs, SQLiteDatabase db) {
    }

    private void createButtonTable(ConnectionSource cs, SQLiteDatabase db) throws SQLException {
        TableUtils.createTableIfNotExists(cs, Button.class);
        List<Button> buttons = new ArrayList<Button>();
        Cursor cursor = db.rawQuery("select * from button_data", new String[]{});
        while (cursor.moveToNext()) {
            Button button = buildButton(cursor);
            buttons.add(button);
        }
        buttonDao.deleteAll();
        for (Button button : buttons) {
            buttonDao.add(button);
        }
    }

    /**
     *
     * 0 define_ID
     * 1 order_ID
     * 2 ID
     * 3 control_ID
     * 4 code_str
     * 5 dis_ch
     * 6 dis_en
     * 7 note
     *
     * @param cursor
     * @return
     */
    private Button buildButton(Cursor cursor) {
        int buttonId = cursor.getInt(2);
        int machineTypeId = cursor.getType(1);
        String order = cursor.getString(2);
        String disCh = cursor.getString(5);
        String disEn = cursor.getString(6);
        String isStudyType = cursor.getString(5);
        String note = cursor.getString(7);
        Button button = new Button();
        button.setButtonId(buttonId);
        button.setMachineTypeId(machineTypeId);
        button.setOrder(order);
        button.setDisCh(disCh);
        button.setDisEn(disEn);
        button.setIsStudyType(isStudyType);
        button.setNote(note);
        return button;
    }

    private void createInfraredVersionTable(ConnectionSource cs, SQLiteDatabase db, InfraredVersion infraredVersion) throws SQLException {
        TableUtils.createTableIfNotExists(cs, InfraredVersion.class);

        infraredVersionDao.deleteAll();
        infraredVersionDao.add(infraredVersion);

    }

    private void createMachineTypeTable(ConnectionSource cs, SQLiteDatabase db) throws SQLException {
//        String sql = "CREATE TABLE machineType(" +
//                "machineTypeId INTEGER primary key autoincrement, " +
//                "nameCh varchar(200), " +
//                "nameEn varchar(200), " +
//                "icon varchar(200)" +
//                ")";
//        sqLiteDatabase.execSQL(sql);
        TableUtils.createTableIfNotExists(cs, MachineType.class);

    }
}
